#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/can.h>
#include <linux/can/raw.h>
#include <net/if.h>


int main(void)
{
	struct sockaddr_can can_addr = {0};
	struct ifreq ifr = {0};
	struct can_frame frame = {0};
	int sockfd = -1;
	int ret = -1;
    int i;

	sockfd = socket(PF_CAN, SOCK_RAW, CAN_RAW);
	if (sockfd < 0) {
		printf("socket errno \n");
		exit(EXIT_FAILURE);
	}

	strcpy(ifr.ifr_name, "can0");
	ioctl(sockfd, SIOCGIFINDEX, &ifr);
	can_addr.can_family = AF_CAN;
	can_addr.can_ifindex = ifr.ifr_ifindex;

	ret = bind(sockfd, (struct sockaddr *)&can_addr, sizeof(can_addr));
	if (ret < 0) {
		printf("bind error\n");
		close(sockfd);
		exit(EXIT_FAILURE);
	}

	while (1) {
		ret = read(sockfd, &frame, sizeof(struct can_frame));
		if (ret != sizeof(frame)) {
			printf("read error\n");
			break;
		}

		for (i=0; i<frame.can_dlc; i++)
			printf("%02x", frame.data[i]);
		printf("\n");
	}

	close(sockfd);
	exit(EXIT_SUCCESS);

}
